﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WhsFacebook.Net.Web.Facebook
{
    public static class FacebookConverter
    {
        private static readonly DateTime _base = new DateTime(1970, 1, 1, 0, 0, 0);

        public static DateTime FromUnixTime(string ts)
        {
            if (string.IsNullOrEmpty(ts))
                throw new ArgumentException("null or empty", "ts");

            return FromUnixTime(Convert.ToDouble(ts));
        }

        public static DateTime FromUnixTime(double ts)
        {
            return _base.AddSeconds(ts);
        }

        public static bool ToBoolean(string s)
        {
            if (string.IsNullOrEmpty(s))
                return false;

            try
            {
                s = ToString(s);

                // parse
                int i;

                if (int.TryParse(s, out i))
                    return (i != 0);

                return Convert.ToBoolean(s);
            }
            catch (FormatException x)
            {
                throw new FormatException("Failed to parse value: '" + s + "'", x);
            }
        }

        public static long ToInt64(string s)
        {
            if (string.IsNullOrEmpty(s))
                return 0;

            try
            {
                return Convert.ToInt64(ToString(s));
            }
            catch (FormatException x)
            {
                throw new FormatException("Failed to parse value: '" + s + "'", x);
            }
        }

        public static string ToString(string s)
        {
            if (string.IsNullOrEmpty(s))
                return null;

            try
            {
                return s.Trim();
            }
            catch (FormatException x)
            {
                throw new FormatException("Failed to parse value: '" + s + "'", x);
            }
        }
    }
}